<template>
  <div class="user-setting-container">
    <t-card class="setting-card">
      <template #header>
        <div class="card-header">
          <h3 class="title">{{ t('pages.user.setting.title') }}</h3>
          <p class="subtitle">{{ t('pages.user.setting.subtitle') }}</p>
        </div>
      </template>

      <t-tabs v-model="activeTab" class="setting-tabs">
        <!-- 个人信息设置 -->
        <t-tab-panel value="profile" :label="t('pages.user.setting.profile')">
          <div class="tab-content">
            <t-form ref="profileForm" :data="profileData" :rules="profileRules" label-width="120px"
              @submit="onProfileSubmit">
              <div class="form-section">
                <h4 class="section-title">{{ t('pages.user.setting.basicInfo') }}</h4>

                <t-form-item name="nickname" :label="t('pages.user.setting.nickname')">
                  <t-input v-model="profileData.nickname" :placeholder="t('pages.user.setting.nicknamePlaceholder')" />
                </t-form-item>
                <t-form-item name="username" :label="t('pages.user.setting.username')">
                  <t-input v-model="profileData.username" disabled />
                </t-form-item>

                <t-form-item name="email" :label="t('pages.user.setting.email')">
                  <t-input v-model="profileData.email" :placeholder="t('pages.user.setting.emailPlaceholder')" />
                </t-form-item>
                <t-form-item name="mobile" :label="t('pages.user.setting.mobile')">
                  <t-input v-model="profileData.mobile" :placeholder="t('pages.user.setting.mobilePlaceholder')" />
                </t-form-item>
              </div>

              <div class="form-actions">
                <t-button type="submit" theme="primary">
                  {{ t('pages.user.setting.save') }}
                </t-button>
                <t-button variant="outline" @click="resetProfile">
                  {{ t('pages.user.setting.reset') }}
                </t-button>
              </div>
            </t-form>
          </div>
        </t-tab-panel>

        <!-- 安全设置 -->
        <t-tab-panel value="security" :label="t('pages.user.setting.security')">
          <div class="tab-content">
            <div class="security-section">
              <h4 class="section-title">{{ t('pages.user.setting.password') }}</h4>

              <t-form ref="passwordForm" :data="passwordData" :rules="passwordRules" label-width="120px"
                @submit="onPasswordSubmit">
                <t-form-item name="oldPassword" :label="t('pages.user.setting.oldPassword')">
                  <t-input v-model="passwordData.oldPassword" type="password"
                    :placeholder="t('pages.user.setting.oldPasswordPlaceholder')" show-password />
                </t-form-item>

                <t-form-item name="newPassword" :label="t('pages.user.setting.newPassword')">
                  <t-input v-model="passwordData.newPassword" type="password"
                    :placeholder="t('pages.user.setting.newPasswordPlaceholder')" show-password />
                </t-form-item>

                <t-form-item name="confirmPassword" :label="t('pages.user.setting.confirmPassword')">
                  <t-input v-model="passwordData.confirmPassword" type="password"
                    :placeholder="t('pages.user.setting.confirmPasswordPlaceholder')" show-password />
                </t-form-item>

                <div class="form-actions">
                  <t-button type="submit" theme="primary">
                    {{ t('pages.user.setting.updatePassword') }}
                  </t-button>
                </div>
              </t-form>
            </div>

          </div>
        </t-tab-panel>

        <!-- 通知设置 -->
        <t-tab-panel value="notification" :label="t('pages.user.setting.notification')">
          <div class="tab-content">
            <div class="notification-section">
              <h4 class="section-title">{{ t('pages.user.setting.notificationSettings') }}</h4>

              <t-form :data="notificationData" label-width="120px">

                <t-form-item :label="t('pages.user.setting.systemNotification')">
                  <t-switch v-model="notificationData.systemNotification" />
                </t-form-item>

                <t-form-item :label="t('pages.user.setting.securityAlerts')">
                  <t-switch v-model="notificationData.securityAlerts" />
                </t-form-item>

                <div class="form-actions">
                  <t-button theme="primary" @click="saveNotificationSettings">
                    {{ t('pages.user.setting.save') }}
                  </t-button>
                </div>
              </t-form>
            </div>
          </div>
        </t-tab-panel>

      </t-tabs>
    </t-card>
  </div>
</template>

<script lang="ts">
export default {
  name: 'UserIndex',
};
</script>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import type { FormInstanceFunctions, FormRule } from 'tdesign-vue-next';
import { t } from '@/locales';
import { getUserProfile, update, updatePassword } from '@/api/userCenter/dept/staff/profile';

const activeTab = ref?.('profile');

// 表单引用
const profileForm = ref<FormInstanceFunctions>();
const passwordForm = ref<FormInstanceFunctions>();

// 个人信息数据
const profileData = reactive({
  nickname: '',
  username: '',
  email: '',
  mobile: '',
  gender: '0',
  avatar: '',
  remark: '',
});

// 密码数据
const passwordData = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
});

// 通知设置数据
const notificationData = reactive({
  emailNotification: true,
  smsNotification: false,
  systemNotification: true,
  securityAlerts: true,
});

// 隐私设置数据
const privacyData = reactive({
  profileVisibility: 'public',
  showEmail: false,
  showMobile: false,
});

// 登录历史
const loginHistory = ref?.([
]);

// 表单验证规则
const profileRules: Record<string, FormRule[]> = {
  nickname: [
    { required: true, message: t('pages.user.setting.nicknameRequired'), type: 'error' },
    { max: 20, message: t('pages.user.setting.nicknameMaxLength'), type: 'error' },
  ],
  email: [
    { required: true, message: t('pages.user.setting.emailRequired'), type: 'error' },
    { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: t('pages.user.setting.emailFormat'), type: 'error' },
  ],
  mobile: [
    { pattern: /^1[3-9]\d{9}$/, message: t('pages.user.setting.mobileFormat'), type: 'error' },
  ],
};

const passwordRules: Record<string, FormRule[]> = {
  oldPassword: [
    { required: true, message: t('pages.user.setting.oldPasswordRequired'), type: 'error' },
  ],
  newPassword: [
    { required: true, message: t('pages.user.setting.newPasswordRequired'), type: 'error' },
    { min: 6, message: t('pages.user.setting.passwordMinLength'), type: 'error' },
  ],
  confirmPassword: [
    { required: true, message: t('pages.user.setting.confirmPasswordRequired'), type: 'error' },
    {
      validator: (val: string) => val === passwordData.newPassword,
      message: t('pages.user.setting.passwordNotMatch'),
      type: 'error',
    },
  ],
};

// 获取用户信息
const loadUserProfile = async () => {
  try {
    const response = await getUserProfile?.();

    const userData = response;

    profileData.nickname = userData.nickname || '';
    profileData.username = userData.username || '';
    profileData.email = userData.email || '';
    profileData.mobile = userData.mobile || '';
    profileData.gender = userData.gender?.toString() || '0';
    profileData.avatar = userData.avatar || '';
    profileData.remark = userData.remark || '';
  } catch (error) {
    MessagePlugin.error(t('pages.user.setting.loadProfileError'));
  }
};

// 提交个人信息
const onProfileSubmit = async (ctx: any) => {
  if (ctx.validateResult === true) {
    try {
      await update({
        nickname: profileData.nickname,
        email: profileData.email,
        mobile: profileData.mobile,
        gender: parseInt?.(profileData.gender),
      });
      MessagePlugin?.success?.(t('pages.user.setting.profileUpdateSuccess'));
    } catch (error) {
      MessagePlugin.error(t('pages.user.setting.profileUpdateError'));
    }
  }
};

// 重置个人信息
const resetProfile = () => {
  loadUserProfile?.();
};

// 提交密码修改
const onPasswordSubmit = async (ctx: any) => {

  if (ctx.validateResult === true) {
    try {
      await updatePassword(passwordData.oldPassword, passwordData.newPassword);
      MessagePlugin?.success?.(t('pages.user.setting.passwordUpdateSuccess'));

      // 清空密码表单
      passwordData.oldPassword = '';
      passwordData.newPassword = '';
      passwordData.confirmPassword = '';
    } catch (error) {
      MessagePlugin.error(t('pages.user.setting.passwordUpdateError'));
    }
  }
};

// 上传头像
const uploadAvatar = () => {
  // 这里可以实现文件上传逻辑
  MessagePlugin.info(t('pages.user.setting.uploadAvatarInfo'));
};

// 保存通知设置
const saveNotificationSettings = () => {
  MessagePlugin?.success?.(t('pages.user.setting.notificationSaveSuccess'));
};

// 保存隐私设置
const savePrivacySettings = () => {
  MessagePlugin?.success?.(t('pages.user.setting.privacySaveSuccess'));
};

// 页面加载时获取用户信息
onMounted(() => {
  loadUserProfile?.();
});
</script>

<style lang="less" scoped>
.user-setting-container {
  padding: 24px;
  background-color: var(--td-bg-color-page);
  min-height: 100vh;

  .setting-card {
    max-width: 1200px;
    margin: 0 auto;
  }

  .card-header {
    .title {
      margin: 0 0 8px 0;
      font-size: 20px;
      font-weight: 600;
      color: var(--td-text-color-primary);
    }

    .subtitle {
      margin: 0;
      font-size: 14px;
      color: var(--td-text-color-secondary);
    }
  }

  .setting-tabs {
    :deep(.t-tabs__nav) {
      border-bottom: 1px solid var(--td-border-level-1-color);
    }
  }

  .tab-content {
    padding: 24px 0;
  }

  .section-title {
    margin: 0 0 24px 0;
    font-size: 16px;
    font-weight: 600;
    color: var(--td-text-color-primary);
    border-bottom: 1px solid var(--td-border-level-1-color);
    padding-bottom: 12px;
  }

  .form-section {
    margin-bottom: 32px;
  }

  .avatar-upload {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .form-actions {
    display: flex;
    gap: 12px;
    margin-top: 24px;
    padding-top: 24px;
    border-top: 1px solid var(--td-border-level-1-color);
  }

  .security-section {
    margin-bottom: 32px;
  }

  .login-history {
    .history-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px;
      border: 1px solid var(--td-border-level-1-color);
      border-radius: 6px;
      margin-bottom: 12px;

      .history-info {
        .login-time {
          font-weight: 500;
          color: var(--td-text-color-primary);
          margin-bottom: 4px;
        }

        .login-ip,
        .login-device {
          font-size: 12px;
          color: var(--td-text-color-secondary);
          margin-bottom: 2px;
        }
      }
    }
  }

  .notification-section,
  .privacy-section {
    max-width: 600px;
  }
}
</style>
